package com.qf.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.common.http.Result;
import com.qf.entity.dto.Goods;
import com.qf.entity.dto.GoodsType;
import com.qf.entity.po.LoginMerchant;
import com.qf.service.impl.GoodsService;
import com.qf.service.impl.GoodsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("list")
    public String toList(Model model, LoginMerchant loginMerchant) {
        model.addAttribute("goodsList", goodsService.getByMerchantId(loginMerchant));
        return "goods/list";
    }

    @RequestMapping("add")
    public String add(Model model,@RequestParam(value = "id",required = false)Long goodsId){
        if (goodsId!=null){
            Goods goods = goodsService.getGoodsById(goodsId);
            model.addAttribute("goods",goods);
        }
        QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(GoodsType::getOrderNum);
        model.addAttribute("goodsTypeList",goodsTypeService.list(wrapper));
        return "goods/add";
    }

    @Value("${upload.path}")
    private String path;

    @RequestMapping("upload")
    @ResponseBody
    public Result<?> upload(MultipartFile file){
        String name = file.getOriginalFilename();
        String ext = name.substring(name.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().concat(ext);
        String filePath = String.format("%s%s",path,fileName);
        File destFile = new File(filePath);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  Result.success(String.format("http://localhost:80/%s", fileName));
    }

    @RequestMapping("save")
    @ResponseBody
    public Result<?> save(Goods goods, LoginMerchant loginMerchant) {
        goodsService.saveOrUpdateByGoods(goods, loginMerchant);
        return Result.success();
    }

    @RequestMapping("del")
    @ResponseBody
    public  Result<?> del(@RequestParam(value="id",required = true) Long id){
        goodsService.removeGoods(id);
        return Result.success();
    }
}
